import type { Context, Next } from "koa";
import errorType from "../constants/error-types.ts";
import service from "../service/user.service.ts";
import bcrypt from "../utils/handle-password.ts";

// 验证用户存在
const verifyUser = async (ctx: Context, next: Next) => {
  // 1.获取用户名和密码
  const { username, password } = ctx.request.body as API.userItem;

  // 2. 判断用户名和密码不能为空
  if (!username || !password) {
    const error = new Error(errorType.USER_OR_PASSWORD_IS_NOT_EMPTY);
    return ctx.app.emit("error", error, ctx);
  }

  // 3.判断这次注册的用户名是没有被注册过的
  const result = await service.getUserByUsername(username);
  if (result) {
    const error = new Error(errorType.USER_IS_EXISIT);
    return ctx.app.emit("error", error, ctx);
  }
  await next();
};

// 密码加密
const handlePassword = async (ctx: Context, next: Next) => {
  // 最佳实践写法
  const requestBody = ctx.request.body as API.userItem;
  const { password } = requestBody;
  requestBody.password = await bcrypt.hashPassword(password);
  await next();
};

export default { verifyUser, handlePassword };
